package com.canoe.text.handler;

import com.canoe.text.common.TextParameterValue;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 使用正则表达式提取内容
 *
 * @author: btm
 * @time: 22:03 2020/9/21
 **/
public final class TextRegexExtractHandler {

    public static void regexExtractHandler(TextParameterValue pv) {
        Pattern regexPattern = Pattern.compile(pv.getRegex());
        try (FileWriter fw = new FileWriter(pv.getTargetFilePath());
                BufferedWriter bw = new BufferedWriter(fw)) {
            for (String fileName : pv.getFileNameList()) {
                try (FileReader fr = new FileReader(pv.getSourceFileBasePath() + "/" + fileName);
                     BufferedReader bf = new BufferedReader(fr);) {
                    String str;
                    // 按行读取字符串
                    while ((str = bf.readLine()) != null) {
                        Matcher matcher = regexPattern.matcher(str);
                        while (matcher.find()) {
                            String target = pv.getPrefix() + matcher.group() + pv.getSuffix();
                            bw.write(target);
                            if (!pv.isSingleLine()) {
                                //每个匹配到的子字符串都占据单独的一行
                                bw.newLine();
                            }
                            if (pv.isFirstOne()) {
                                //只提取每一行的第一个匹配的子字符串，所以循环一次就推出
                                break;
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
